import React from 'react';
import PropTypes from 'prop-types';
import {injectIntl} from './intl';
import {Card, Row, Col, Table, Divider} from 'antd';
import {conventEnumValueToString, formatAmount, formatDateTime, exportDownload} from '../utils';
import {paymentType, transportType, partOrderPriceTerms, currency, packingType} from '../Enum';
import DescriptionList from 'ant-design-pro/lib/DescriptionList';
import {TABLE, PAGINATION_OPTIONS, DATE_FORMAT} from '../constants';
import {renderBoolean} from './utils';
const {Description} = DescriptionList;
import Ellipsis from 'ant-design-pro/lib/Ellipsis';
import styles from './style.css';
import Export from '../common/Export';
import {exportPartInvoices} from './api';
/* eslint-disable react/prefer-stateless-function */
const sortByName = name => (a, b) => {
    if(a[name] && b[name])
        return a[name].localeCompare(b[name]);
    return 0;
};
const rowKey = record => `${record.packingListId}${record.partCode}`;
class Detail extends React.PureComponent {
    onPackingTableFooter = () => {
        const {packingLists = []} = this.props.detail;
        const length = packingLists.length;
        const {totalNetWeight, totalGrossWeight, totalVolume} = packingLists.reduce((a, b) => ({
            totalVolume: a.totalVolume + b.volume,
            totalNetWeight: a.totalNetWeight + b.netWeight,
            totalGrossWeight: a.totalGrossWeight + b.grossWeight,
        }), {
            totalNetWeight: 0,
            totalGrossWeight: 0,
            totalVolume: 0,
        });

        return (<React.Fragment>   
            <span>{`${this.props.intl.formatMessage({
                id: 'detail.footer.length',
                defaultMessage: '总包装数:'
            })}${length}`}</span>
            <Divider type="vertical" />
            <span>{`${this.props.intl.formatMessage({
                id: 'add.footer.totalVolume',
                defaultMessage: '总体积（m³）:'
            })}${formatAmount(totalVolume)}`}</span>
            <Divider type="vertical" />
            <span>{`${this.props.intl.formatMessage({
                id: 'add.footer.totalNetWeight',
                defaultMessage: '总净重（kg）:'
            })}${formatAmount(totalNetWeight)}`}</span>
            <Divider type="vertical" />
            <span>{`${this.props.intl.formatMessage({
                id: 'add.footer.totalGrossWeight',
                defaultMessage: '总毛重（kg）:'
            })}${formatAmount(totalGrossWeight)}`}</span>
        </React.Fragment>);
    }
    onDetailTableFooter = () => {
        const {details = []} = this.props.detail;
        const {totalNum} = details.reduce((a, b) => ({
            totalNum: a.totalNum + b.quantity,
        }), {
            totalNum: 0,
        });
        const totalKind = details.length;
        return (<React.Fragment>
            <span>{`${this.props.intl.formatMessage({
                id: 'detail.footer.totalKind',
                defaultMessage: '总品种数:'
            })}${totalKind}`}</span>
            <Divider type="vertical" />
            <span>{`${this.props.intl.formatMessage({
                id: 'detail.footer.totalNum',
                defaultMessage: '总数量:'
            })}${totalNum}`}</span>
            
        </React.Fragment>);
    }
    onClickExport = () => {
        this.setState({loading: true});
        exportPartInvoices(this.props.id).then(res => {
            this.setState({
                loading: false
            });
            exportDownload(res);
        });
    }
    render() {
        const {details = [], packingLists = []} = this.props.detail;
        const packingColumns = [
            {
                title: this.props.intl.formatMessage({
                    id: 'commonDetail.packingColumns.pickingListCodes',
                    defaultMessage: '备料单号'
                }),
                dataIndex: 'pickingListCodes',
                render: text => text && text.length > 30 ? <Ellipsis length={36} tooltip>
                    {text}
                </Ellipsis> : text
            }, {
                title: this.props.intl.formatMessage({
                    id: 'commonDetail.packingColumns.palletCodes',
                    defaultMessage: '托盘号'
                }),
                dataIndex: 'palletCodes',
                render: text => text && text.length > 30 ? <Ellipsis length={36} tooltip>
                    {text}
                </Ellipsis> : text
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'commonDetail.packingColumns.packingType',
                    defaultMessage: '包装类型'
                }),
                dataIndex: 'packingType',
                sorter: sortByName('packingType'),
                render: text => conventEnumValueToString(packingType, text)
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'commonDetail.packingColumns.container',
                    defaultMessage: '包装规格'
                }),
                dataIndex: 'container',
            },
            {
                title: <div className={styles.column}>{this.props.intl.formatMessage({
                    id: 'commonDetail.packingColumns.length',
                    defaultMessage: '长'
                })}<br/>{this.props.intl.formatMessage({
                    id: 'commonDetail.packingColumns.mm',
                    defaultMessage: '（mm）'
                })}</div>,
                dataIndex: 'length',
                width: 80
            },
            {
                title: <div className={styles.column}>{this.props.intl.formatMessage({
                    id: 'commonDetail.packingColumns.width',
                    defaultMessage: '宽'
                })}<br/>{this.props.intl.formatMessage({
                    id: 'commonDetail.packingColumns.mm',
                    defaultMessage: '（mm）'
                })}</div>,
                dataIndex: 'width',
                width: 80
            },
            {
                title: <div className={styles.column}>{this.props.intl.formatMessage({
                    id: 'commonDetail.packingColumns.height',
                    defaultMessage: '高'
                })}<br/>{this.props.intl.formatMessage({
                    id: 'commonDetail.packingColumns.mm',
                    defaultMessage: '（mm）'
                })}</div>,
                dataIndex: 'height',
                width: 80
            },
            {
                title: <div className={styles.column}>{this.props.intl.formatMessage({
                    id: 'commonDetail.packingColumns.volume',
                    defaultMessage: '体积'
                })}<br/>{this.props.intl.formatMessage({
                    id: 'commonDetail.packingColumns.m3',
                    defaultMessage: '（m3）'
                })}</div>,
                dataIndex: 'volume',
                render: text => formatAmount(text, 3),
                width: 80
            },
            {
                title: <div className={styles.column}>{this.props.intl.formatMessage({
                    id: 'commonDetail.packingColumns.netWeight',
                    defaultMessage: '净重'
                })}<br/>{this.props.intl.formatMessage({
                    id: 'commonDetail.packingColumns.kg',
                    defaultMessage: '（kg）'
                })}</div>,
                dataIndex: 'netWeight',
                render: text => formatAmount(text, 3),
                width: 80
            },
            {
                title: <div className={styles.column}>{this.props.intl.formatMessage({
                    id: 'commonDetail.packingColumns.grossWeight',
                    defaultMessage: '毛重'
                })}<br/>{this.props.intl.formatMessage({
                    id: 'commonDetail.packingColumns.kg',
                    defaultMessage: '（kg）'
                })}</div>,
                dataIndex: 'grossWeight',
                render: text => formatAmount(text, 3),
                width: 80
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'commonDetail.packingColumns.containerNo',
                    defaultMessage: '柜图号'
                }),
                dataIndex: 'containerNo',
                sorter: sortByName('containerNo')
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'commonDetail.packingColumns.remark',
                    defaultMessage: '备注'
                }),
                dataIndex: 'remark',
            }
        ];

        const columns = [
            {
                title: this.props.intl.formatMessage({
                    id: 'commonDetail.column.partSaleOrderCode',
                    defaultMessage: '订单号'
                }),
                dataIndex: 'partSaleOrderCode',
                sorter: sortByName('partSaleOrderCode')
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'commonDetail.packingColumns.pickingListCodes',
                    defaultMessage: '备料单号'
                }),
                dataIndex: 'pickingListCode',
                sorter: sortByName('pickingListCode')
            }, {
                title: this.props.intl.formatMessage({
                    id: 'commonDetail.packingColumns.palletCodes',
                    defaultMessage: '托盘号'
                }),
                dataIndex: 'palletCode',
                sorter: sortByName('palletCode')
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'commonDetail.column.partCode',
                    defaultMessage: '备件编号'
                }),
                dataIndex: 'partCode',
                sorter: sortByName('partCode')
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'commonDetail.column.partName',
                    defaultMessage: '备件名称'
                }),
                dataIndex: 'partName',
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'commonDetail.column.quantity',
                    defaultMessage: '数量'
                }),
                dataIndex: 'quantity',
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'commonDetail.column.price',
                    defaultMessage: '单价'
                }),
                dataIndex: 'price',
                className: styles.textAlign,
                render: text => formatAmount(text)
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'commonDetail.column.pricingDate',
                    defaultMessage: '定价日期'
                }),
                dataIndex: 'pricingDate',
                render: text => formatDateTime(text, DATE_FORMAT)
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'commonDetail.column.totalAmount',
                    defaultMessage: '总价'
                }),
                dataIndex: 'totalAmount',
                className: styles.textAlign,
                render: text => formatAmount(text)
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'commonDetail.column.perNetWeight',
                    defaultMessage: '单位净重'
                }),
                dataIndex: 'perNetWeight',
                render: text => formatAmount(text, 3)
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'commonDetail.column.netWeight',
                    defaultMessage: '总净重'
                }),
                dataIndex: 'netWeight',
                render: text => formatAmount(text, 3)
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'commonDetail.column.perGrossWeight',
                    defaultMessage: '单位毛重'
                }),
                dataIndex: 'perGrossWeight',
                render: text => formatAmount(text, 3)
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'commonDetail.column.grossWeight',
                    defaultMessage: '总毛重'
                }),
                dataIndex: 'grossWeight',
                render: text => formatAmount(text, 3)
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'commonDetail.column.oldPartCode',
                    defaultMessage: '被替换备件编号'
                }),
                dataIndex: 'oldPartCode',
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'commonDetail.column.discountPrice',
                    defaultMessage: '折扣后单价'
                }),
                dataIndex: 'discountPrice',
                className: styles.textAlign,
                render: text => formatAmount(text)
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'commonDetail.column.discountAmount',
                    defaultMessage: '折扣后总价'
                }),
                dataIndex: 'discountAmount',
                className: styles.textAlign,
                render: text => formatAmount(text)
            },
        ];

        const pagination = {
            total: details.length,
            ...PAGINATION_OPTIONS
        };
        const packingPagination = {
            total: packingLists.length,
            ...PAGINATION_OPTIONS
        };
        return (
            <div>
                <Card>
                    <DescriptionList size="large" title={<Row><Col span={6}>{this.props.intl.formatMessage({
                        id: 'commonDetail.buyer.title',
                        defaultMessage: '买方基础信息'
                    })}</Col>
                    <Col className={styles.optionBtn} span={18}>{this.props.operations}</Col></Row>}>
                        <Description
                            term={this.props.intl.formatMessage({
                                id: 'commonDetail.info.code',
                                defaultMessage: '发票号'
                            })}>
                            {this.props.detail.code}
                        </Description>
                        <Description
                            term={this.props.intl.formatMessage({
                                id: 'commonDetail.info.brandCode',
                                defaultMessage: '品牌编号'
                            })}>
                            {this.props.detail.brandCode}
                        </Description>
                        <Description
                            term={this.props.intl.formatMessage({
                                id: 'commonDetail.info.dealerCode',
                                defaultMessage: '总代编号'
                            })}>
                            {this.props.detail.dealerCode}
                        </Description>
                        <Description
                            term={this.props.intl.formatMessage({
                                id: 'commonDetail.info.receiverCode',
                                defaultMessage: '送达方编号'
                            })}>
                            {this.props.detail.receiverCode}
                        </Description>
                        <Description
                            term={this.props.intl.formatMessage({
                                id: 'commonDetail.info.country',
                                defaultMessage: '国家'
                            })}>
                            {this.props.detail.country}
                        </Description>
                        <Description
                            term={this.props.intl.formatMessage({
                                id: 'commonDetail.info.currency',
                                defaultMessage: '结算币种'
                            })}>
                            {conventEnumValueToString(currency, this.props.detail.currency)}
                        </Description>
                    </DescriptionList>
                    <DescriptionList col={1} className={styles.mgtp} size="large">
                        <Description term={this.props.intl.formatMessage({
                            id: 'commonDetail.info.partSaleOrderCodes',
                            defaultMessage: '订单号'
                        })}>
                            {this.props.detail.partSaleOrderCodes && this.props.detail.partSaleOrderCodes.length > 100 ? <Ellipsis length={100} tooltip>
                                {this.props.detail.partSaleOrderCodes}
                            </Ellipsis> : this.props.detail.partSaleOrderCodes
                            }
                        </Description>
                    </DescriptionList>
                    <Divider />
                    <DescriptionList size="large" title={this.props.intl.formatMessage({
                        id: 'commonDetail.buyerContact.title',
                        defaultMessage: '买方联系方式'
                    })}>
                        <Description
                            term={this.props.intl.formatMessage({
                                id: 'commonDetail.info.buyer',
                                defaultMessage: '买方名称'
                            })}>
                            {this.props.detail.buyer}
                        </Description>
                        <Description
                            term={this.props.intl.formatMessage({
                                id: 'commonDetail.info.buyerNumber',
                                defaultMessage: '联系电话'
                            })}>
                            {this.props.detail.buyerNumber}
                        </Description>
                        <Description
                            term={this.props.intl.formatMessage({
                                id: 'commonDetail.info.buyerFAX',
                                defaultMessage: '买方传真'
                            })}>
                            {this.props.detail.buyerFAX}
                        </Description>
                        <Description
                            term={this.props.intl.formatMessage({
                                id: 'commonDetail.info.buyerCantact',
                                defaultMessage: '买方联系人'
                            })}>
                            {this.props.detail.buyerCantact}
                        </Description>
                    </DescriptionList>
                    <DescriptionList col={1} className={styles.mgtp} size="large">
                        <Description
                            term={this.props.intl.formatMessage({
                                id: 'commonDetail.info.buyerAddress',
                                defaultMessage: '买方地址'
                            })}>
                            {this.props.detail.buyerAddress}
                        </Description>
                    </DescriptionList>
                    <Divider />
                    <DescriptionList size="large" title={this.props.intl.formatMessage({
                        id: 'commonDetail.sellerContact.title',
                        defaultMessage: '卖方联系方式'
                    })}>
                        <Description
                            term={this.props.intl.formatMessage({
                                id: 'commonDetail.info.seller',
                                defaultMessage: '卖方名称'
                            })}>
                            {this.props.detail.seller}
                        </Description>
                        <Description
                            term={this.props.intl.formatMessage({
                                id: 'commonDetail.info.sellerNumber',
                                defaultMessage: '卖方电话'
                            })}>
                            {this.props.detail.sellerNumber}
                        </Description>
                        <Description
                            term={this.props.intl.formatMessage({
                                id: 'commonDetail.info.sellerFAX',
                                defaultMessage: '卖方传真'
                            })}>
                            {this.props.detail.sellerFAX}
                        </Description>
                    </DescriptionList>
                    <DescriptionList col={1} className={styles.mgtp} size="large">
                        <Description
                            term={this.props.intl.formatMessage({
                                id: 'commonDetail.info.sellerAddress',
                                defaultMessage: '卖方地址'
                            })}>
                            {this.props.detail.sellerAddress}
                        </Description>
                    </DescriptionList>
                    <Divider />
                    <DescriptionList size="large" title={this.props.intl.formatMessage({
                        id: 'commonDetail.sellerContact.title1',
                        defaultMessage: '发运付款信息'
                    })}>
                        <Description
                            term={this.props.intl.formatMessage({
                                id: 'commonDetail.info.origin',
                                defaultMessage: '起运地'
                            })}>
                            {this.props.detail.origin}
                        </Description>
                        <Description
                            term={this.props.intl.formatMessage({
                                id: 'commonDetail.info.destination',
                                defaultMessage: '目的地'
                            })}>
                            {this.props.detail.destination}
                        </Description>
                        <Description
                            term={this.props.intl.formatMessage({
                                id: 'commonDetail.info.paymentType',
                                defaultMessage: '付款方式'
                            })}>
                            {conventEnumValueToString(paymentType, this.props.detail.paymentType)}
                        </Description>
                        <Description
                            term={this.props.intl.formatMessage({
                                id: 'commonDetail.info.priceTerms',
                                defaultMessage: '价格条款'
                            })}>
                            {conventEnumValueToString(partOrderPriceTerms, this.props.detail.priceTerms)}
                        </Description>
                        <Description
                            term={this.props.intl.formatMessage({
                                id: 'commonDetail.info.shipmentType',
                                defaultMessage: '运输方式'
                            })}>
                            {conventEnumValueToString(transportType, this.props.detail.shipmentType)}
                        </Description>
                        {
                            this.props.detail.shipmentType === transportType.快递 &&
                            <Description
                                term={this.props.intl.formatMessage({
                                    id: 'commonDetail.info.carriers',
                                    defaultMessage: '快递公司'
                                })}>
                                {this.props.detail.expressCompanyCode}
                            </Description>
                        }
                    </DescriptionList>
                    <Divider />
                    <DescriptionList size="large" title={this.props.intl.formatMessage({
                        id: 'commonDetail.fee.title',
                        defaultMessage: '运费和折扣信息'
                    })}>
                        <Description
                            term={this.props.intl.formatMessage({
                                id: 'commonDetail.info.itemCount',
                                defaultMessage: '备件品种数'
                            })}>
                            {this.props.detail.itemCount}
                        </Description>
                        <Description
                            term={this.props.intl.formatMessage({
                                id: 'commonDetail.info.totalQuantity',
                                defaultMessage: '备件总数量'
                            })}>
                            {this.props.detail.totalQuantity}
                        </Description>
                        <Description
                            term={this.props.intl.formatMessage({
                                id: 'commonDetail.info.totalAmount',
                                defaultMessage: '备件总金额'
                            })}>
                            {formatAmount(this.props.detail.totalAmount)}
                        </Description>
                        <Description
                            term={this.props.intl.formatMessage({
                                id: 'commonDetail.info.freight',
                                defaultMessage: '运费'
                            })}>
                            {formatAmount(this.props.detail.freight)}
                        </Description>
                        <Description
                            term={this.props.intl.formatMessage({
                                id: 'commonDetail.info.insurance',
                                defaultMessage: '保费'
                            })}>
                            {formatAmount(this.props.detail.insurance)}
                        </Description>
                        <Description
                            term={this.props.intl.formatMessage({
                                id: 'commonDetail.info.discountAmount',
                                defaultMessage: '折扣金额'
                            })}>
                            {formatAmount(this.props.detail.discountAmount)}
                        </Description>
                        <Description
                            term={this.props.intl.formatMessage({
                                id: 'commonDetail.info.otherAmount',
                                defaultMessage: '其他金额'
                            })}>
                            {formatAmount(this.props.detail.otherAmount)}
                        </Description>
                        <Description
                            term={this.props.intl.formatMessage({
                                id: 'commonDetail.info.claimAmount',
                                defaultMessage: '索赔金额'
                            })}>
                            {formatAmount(this.props.detail.claimAmount)}
                        </Description>
                        <Description
                            term={this.props.intl.formatMessage({
                                id: 'commonDetail.info.differentAmount',
                                defaultMessage: '报关差异金额'
                            })}>
                            {formatAmount(this.props.detail.differentAmount)}
                        </Description>
                        <Description
                            term={this.props.intl.formatMessage({
                                id: 'commonDetail.info.isBonus',
                                defaultMessage: '是否使用返利'
                            })}>
                            {renderBoolean(this.props.detail.isBonus)}
                        </Description>
                        <Description
                            term={this.props.intl.formatMessage({
                                id: 'commonDetail.info.totalDiscount',
                                defaultMessage: '折扣总金额'
                            })}>
                            {formatAmount(this.props.detail.totalDiscount)}
                        </Description>
                        <Description
                            term={this.props.intl.formatMessage({
                                id: 'commonDetail.info.bonusAmount',
                                defaultMessage: '返利金额'
                            })}>
                            {formatAmount(this.props.detail.bonusAmount)}
                        </Description>
                        <Description
                            term={this.props.intl.formatMessage({
                                id: 'commonDetail.info.invoiceAmount',
                                defaultMessage: '发票金额'
                            })}>
                            {formatAmount(this.props.detail.invoiceAmount)}
                        </Description>
                    </DescriptionList>
                    <DescriptionList col={1} className={styles.mgtp} size="large">
                        <Description
                            term={this.props.intl.formatMessage({
                                id: 'commonDetail.info.discountReason',
                                defaultMessage: '折扣原因'
                            })}>
                            {this.props.detail.discountReason}
                        </Description>
                    </DescriptionList>
                </Card>
                <Card
                    title={this.props.intl.formatMessage({
                        id: 'commonDetail.packingLists.title',
                        defaultMessage: '箱单发票包装清单'
                    })}
                    bordered={false}>
                    <Table className="white-space-nowrap"
                        rowKey="id"
                        columns={packingColumns}
                        pagination={false}
                        dataSource={packingLists}
                        footer={this.onPackingTableFooter}
                        {...TABLE} />
                </Card>
                <Card
                    title={this.props.intl.formatMessage({
                        id: 'commonDetail.details.title',
                        defaultMessage: '箱单发票备件清单'
                    })}
                    bordered={false}
                    extra={<Export key="export" size="small" title={this.props.intl.formatMessage({
                        id: 'newPanel.operation.exportDetail',
                        defaultMessage: '导出清单'
                    })} exportRequest={this.onClickExport} />}>
                    <Table className="white-space-nowrap"
                        rowKey={rowKey}
                        columns={columns}
                        pagination={false}
                        footer={this.onDetailTableFooter}
                        dataSource={details}
                        {...TABLE} />
                </Card>
            </div>
        );
    }
}

Detail.defaultProps = {
    detail: {},
};

Detail.propTypes = {
    detail: PropTypes.object,
    id: PropTypes.string,
    intl: PropTypes.object,
    isDetail: PropTypes.bool,
    operations: PropTypes.any,
};
export default injectIntl(Detail);
